package com.caijing.caijingxueyuanxd.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ImageFileController {
    @GetMapping("/static-files")
    public List<Map<String, String>> getStaticFiles() throws IOException {
        List<Map<String, String>> files = new ArrayList<>();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        // 扫描所有静态资源
        Resource[] resources = resolver.getResources("classpath:/static/**/*.*");

        for (Resource resource : resources) {
            if (resource.isReadable()) {
                // 获取文件名
                String filename = resource.getFilename();

                // 构建相对路径（去除static前缀）
                String relativePath = resource.getURI().toString()
                        .replaceFirst(".*static/", "");

                // 构建HTTP类型的URL
                String url = ServletUriComponentsBuilder.fromCurrentContextPath()
                        .path("/static/")
                        .path(relativePath)
                        .toUriString();

                // 如果URL以https开头，替换为http
                if (url.startsWith("https://")) {
                    url = "http://" + url.substring(8);
                }

                Map<String, String> fileInfo = new HashMap<>();
                fileInfo.put("filename", filename);
                fileInfo.put("url", url);
                files.add(fileInfo);
            }
        }

        return files;
    }

}
